package edu.bw.resolver;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

@Component
@Log4j2(topic = "fileLogger")
public class MyExceptionResolver implements HandlerExceptionResolver {
    /**
     * 一旦项目中出现异常就会调用MyExceptionResolver解析器中的resolveException方法
     *
     * @param request  当前请求
     * @param response 当前响应
     * @param handler  抛出异常的Hanlder对象
     * @param ex       接受到的Hanlder中抛出的异常对象
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                         Object handler, Exception ex) {
        //控制台输出日志:出现异常的handler
//        log.info(handler);
        System.out.println(handler);

        //将错误信息记录到日志文件
        log.error(handler+":"+ex.getMessage(),ex);


        //根据实际需求转到不同的错误页面
        /*if (ex instanceof  XXX) {
            //转页面
        } else if (ex instanceof XXX) {
            //转到另一个页面
        }*/


        return new ModelAndView("error");
    }
}
